//app.js
import {
  dlc
} from './utils/tools.js'
App({
  onLaunch: function (e) {
    // 检查更新
    this.autoUpdate();
    // 创建dlc实例
    this.dlc = new dlc();
    this.overShare()
  },
  onShow: function (e) {
    const that = this;
    // 分别对安卓和Ios的系统做区分
    const info = wx.getSystemInfoSync()
    // that.globalData.system = 1
    if (info.platform === 'android') {
      that.globalData.system = 1
    } else {
      // ios 需要执行的代码	iPhone 12<iPhone13,2>
      that.globalData.system = 0
      that.globalData.phone = info.model
    }
    if(!that.dlc.gain('theme_color')){
      wx.setStorageSync('theme_color', '#F24660')
    }
    //监听页面切换
    wx.onAppRoute(function (res) {
      
    })
  },
  watch(cb) {
    const that = this;
    var obj = this.globalData;
    Object.defineProperty(obj, "token", { //这里的 data 对应 上面 globalData 中的 data
      configurable: true,
      enumerable: true,
      set: function (value) { //动态赋值，传递对象，为 globalData 中对应变量赋值
        typeof cb == "function" && cb();
      },
      get: function () { //获取全局变量值，直接返回全部
        return that.globalData;
        typeof cb == "function" && cb();
      }
    })
  },
  overShare: function () {
    const that = this;
    //监听路由切换
    //间接实现全局设置分享内容
    wx.onAppRoute(function (res) {
      //获取加载的页面
      let pages = getCurrentPages(),
        //获取当前页面的对象
        view = pages[pages.length - 1],
        data;
      // console.log(view)
      if (view) {
        data = view.data;
        // console.log('是否重写分享方法', data.isOverShare);
        if (!data.isOverShare) {
          data.isOverShare = true;
          view.onShareAppMessage = function () {
            console.log(view)
            //你的分享配置
            return {
              title: that.dlc.gain('brand_title') ? that.dlc.gain('brand_title') : '集轻松',
              path: "/pages/home_page/index?brand=" + (that.dlc.gain('brand') ? that.dlc.gain('brand') : '') + '&brand_title=' + (that.dlc.gain('brand_title') ? that.dlc.gain('brand_title') : '')
            };
          }
        }
      }
    })
  },
  /*
   cb(flag, name, result, data)
   name 为自已定义的标识符，回调会原样返回
   flag = 1  选择文件成功，result选择的结果，状态显示为正在上传文件
   flag = -1 选择文件失败，result为失败结果
   flag = 2  为上传文件成功，result为文件id传给服务器, data为上传文件src等详细数据
   */
  uploadFile: function (name, type, cb, data, params, count, compress) { //name自定标识,cb回调函数,data其它表单json,params chooseImage参数{count:1}/
    // data.token = wx.getStorageSync('token') ? wx.getStorageSync('token') : '';
    var that = this;
    var count = count ? count : 1;
    var chooseParams = {
      count: count,
      success: (res1) => {
        typeof cb == "function" && cb(1, name, res1);
        var tempFilePaths = res1.tempFiles;
        for (var tempFileIndex in tempFilePaths) {
          var filePath = tempFilePaths[tempFileIndex].path;
          var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
          let cos = uploadFiles(type);
          let now = new Date();
          let now_time = now.getTime();
          let y = now.getFullYear();
          let m = ("0" + (now.getMonth() + 1)).slice(-2);
          let d = ("0" + now.getDate()).slice(-2);
          let time = y + m + d
          let maxsize = Math.floor(tempFilePaths[tempFileIndex].size)
          if (maxsize > 1048576) {
            let numds = parseInt(maxsize / 1048576)
            let numded = parseInt(100 / numds)
            wx.compressImage({
              src: filePath, // 图片路径
              quality: numded, // 压缩质量
              compressedWidth: 750,
              success: (rmsg) => {
                console.log(rmsg)
                filePath = rmsg.tempFilePath;
                // 检测图片大小
                // wx.getFileSystemManager().stat({
                //     path: filePath,
                //     success: (statRes) => {
                //         console.log(statRes)
                //         let fileSize = statRes.stats.size;
                //         console.log(fileSize)
                //         if (fileSize > 1024 * 1024) {
                //             console.log('图片超过1MB，继续压缩...');
                //             // 递归调用自身继续压缩
                //             // 注意设置递归限制条件，防止栈溢出
                //         } else {
                //             console.log('图片压缩完成，大小为：' + (fileSize / 1024).toFixed(2) + 'KB');
                //             // 使用compressedFilePath作为最终的压缩图片路径
                //         }
                //     }
                // })
                cos.postObject({
                  Region: JSON.parse(that.dlc.gain(type)).region,
                  Bucket: JSON.parse(that.dlc.gain(type)).bucketname,
                  Key: type + '/' + time + '/' + now_time + that.dlc.randomn(5) + filename,
                  FilePath: filePath,
                  onProgress: function (info) {
                    // console.log(info)
                    // console.log(JSON.stringify(info));上传进度
                  }
                }, function (err, data) {
                  console.log(err)
                  console.log(data)
                  if (err) {
                    that.toast('您当前上传网络不佳，导致上传失败')
                  } else if (data.statusCode == 200) {
                    typeof cb == "function" && cb(2, name, 'https://' + data.Location);
                  }
                });
              }
            })
          } else {
            cos.postObject({
              Region: JSON.parse(that.dlc.gain(type)).region,
              Bucket: JSON.parse(that.dlc.gain(type)).bucketname,
              Key: type + '/' + time + '/' + now_time + that.dlc.randomn(5) + filename,
              FilePath: filePath,
              onProgress: function (info) {
                // console.log(info)
                // console.log(JSON.stringify(info));上传进度
              }
            }, function (err, data) {
              console.log(err)
              console.log(data)
              if (err) {
                that.toast('您当前上传网络不佳，导致上传失败')
              } else if (data.statusCode == 200) {
                typeof cb == "function" && cb(2, name, 'https://' + data.Location);
              }
            });
          }
        }
      },
      fail(res1) {
        typeof cb == "function" && cb(-1, name, res1);
      }
    };
    var chooseParam = {
      count: count,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log(res)
        let video_time = res.tempFiles[0].duration;
        if (video_time > 600) {
          that.toast('上传视频不能超过10分钟')
          return false
        }
        let thumbTempFilePath = res.tempFiles[0].thumbTempFilePath;
        console.log(res)
        let maxsize = Math.floor(res.tempFiles[0].size)
        console.log(parseInt(maxsize / 1024 / 1024))
        if (parseInt(maxsize / 1024 / 1024) > 500) {
          that.toast('上传视频不能超过500M')
          return false
        }
        typeof cb == "function" && cb(1, name, thumbTempFilePath, res.tempFiles[0].duration);
        var tempFilePaths = res.tempFiles;
        for (var tempFileIndex in tempFilePaths) {
          let video_time = tempFilePaths[tempFileIndex].duration;
          if (video_time > 600) {
            that.toast('上传视频不能超过10分钟')
            return false
          }
          var filePath = tempFilePaths[tempFileIndex].tempFilePath;
          console.log(filePath)
          var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
          let height = tempFilePaths[tempFileIndex].height;
          let width = tempFilePaths[tempFileIndex].width;
          let anyway = height > width ? 'vertical' : 'horizontal';
          let cos = uploadFiles(type);
          let now = new Date();
          let now_time = now.getTime();
          let y = now.getFullYear();
          let m = ("0" + (now.getMonth() + 1)).slice(-2);
          let d = ("0" + now.getDate()).slice(-2);
          let time = y + m + d
          console.log(filename)
          cos.postObject({
            Region: JSON.parse(that.dlc.gain(type)).region,
            Bucket: JSON.parse(that.dlc.gain(type)).bucketname,
            Key: type + '/' + time + '/' + now_time + that.dlc.randomn(5) + new Date().getTime() + '.m3u8',
            FilePath: filePath,
            onProgress: function (info) {
              console.log(info)
              var percent = parseInt(info.percent * 10000) / 100;
              var speed = parseInt((info.speed / 1024 / 1024) * 100) / 100;
              // console.log('进度：' + percent + '%; 速度：' + speed + 'Mb/s;');
              that.loading('进度：' + parseInt(percent) + '%');
            }
          }, function (err, data) {
            console.log(err)
            console.log(data)
            if (err) {
              that.toast('您当前上传网络不佳，导致上传失败')
            } else if (data.statusCode == 200) {
              let url = data.Location;
              let urls = url.substring(0, url.length - 5);
              typeof cb == "function" && cb(2, name, 'https://' + urls + '_lechuang.m3u8', anyway, filePath, url);
            }
          });
        }
      }
    }
    if (typeof params == 'object') {
      for (var i in params) chooseParams[i] = params[i];
    }
    if (type === 'pictur') {
      wx.chooseImage(chooseParams)
    } else if (type === 'video') {
      wx.chooseMedia(chooseParam)
    }
  },
  //请求接口，带token
  wxRequest(url, data, successCB, type, data_type) {
    let that = this;
    var requestUrl = (that.dlc.gain('brand') ? 'https://' + that.dlc.gain('brand') : that.dlc.host) + url;
    var requestMethod = type ? type : 'POST';
    var requestConType = data_type ? 'application/x-www-form-urlencoded' : 'application/json'
    if (typeof url != 'string') {
      requestUrl = url.url;
      requestMethod = url.method;
      requestConType = url.conType;
    }
    if (type === 'get') {
      data.time = new Date().getTime()
    }
    wx.request({
      url: requestUrl,
      header: {
        'content-type': requestConType,
        "accessToken": that.dlc.gain('token') ? that.dlc.gain('token') : '',
        "vhost": that.dlc.gain('brand') ? that.dlc.gain('brand') : 'n.tuku321.com'
      },
      data: data,
      method: requestMethod,
      success: (res) => {
        wx.hideLoading()
        // console.log(res)
        if (res.statusCode == 500) {
          this.globalData.token = ""
          wx.removeStorageSync('token')
        } else {
          if (res.data.code == 401) { //登陆过期
            // that.toast('请先授权登录')
            typeof successCB == "function" && successCB(res.data);
            // wx.clearStorageSync()
          } else { //报错
            typeof successCB == "function" && successCB(res.data);
          }
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  //请求接口，不带token
  wxRequests(url, data, successCB, type, data_type) {
    let that = this;
    var requestUrl = that.dlc.host + url;
    var requestMethod = type ? type : 'POST';
    var requestConType = data_type ? 'application/x-www-form-urlencoded' : 'application/json'
    if (typeof url != 'string') {
      requestUrl = url.url;
      requestMethod = url.method;
      requestConType = url.conType;
    }
    if (type === 'get') {
      data.time = new Date().getTime()
    }
    wx.request({
      url: requestUrl,
      header: {
        'content-type': requestConType,
      },
      data: data,
      method: requestMethod,
      success: (res) => {
        wx.hideLoading()
        // console.log(res)
        if (res.statusCode == 401) {
          that.clearstoranges()
          that.globalData.token = ''
          that.toast('登陆过期，请重新授权登录')
          let datas = {
            code: 401,
            data: {},
            message: '请先授权登录'
          }
          // typeof successCB == "function" && successCB(datas);
        } else {
          if (res.data.code == 401) { //登陆过期
            // that.toast('请先授权登录')
            wx.clearStorageSync()
          } else { //报错
            typeof successCB == "function" && successCB(res.data);
          }
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  //请求接口，长整型
  wxRequestd(url, data, successCB, type, data_type) {
    let that = this;
    var requestUrl = that.dlc.host + url;
    var requestMethod = type ? type : 'POST';
    var requestConType = data_type ? 'application/x-www-form-urlencoded' : 'application/json'
    if (typeof url != 'string') {
      requestUrl = url.url;
      requestMethod = url.method;
      requestConType = url.conType;
    }
    let whiteList = ['/auth/social/login']
    let authorization = ''
    if (whiteList.includes(url)) {
      authorization = ''
    } else {
      authorization = that.dlc.gain('token') ? that.dlc.gain('token') : ''
    }
    wx.request({
      url: requestUrl,
      header: {
        'content-type': requestConType,
        "Authorization": authorization
      },
      dataType: 'text',
      responseType: 'text',
      data: data,
      method: requestMethod,
      success: (res) => {
        wx.hideLoading()
        // console.log('login,', res);
        let redatas = that.handleResData(res.data)
        if (res.statusCode == 401) {
          that.globalData.token = ''
          wx.clearStorageSync()
          that.toast('登陆过期，请授权登录')
          let datas = {
            code: 401,
            data: {},
            message: '登录过期'
          }
          typeof successCB == "function" && successCB(datas);
        } else {
          if (redatas.code == 401) { //登陆过期
            that.toast('请先授权登录')
            wx.clearStorageSync()
          } else if (redatas.code == 200 || redatas.code == 407) { //未报错
            typeof successCB == "function" && successCB(redatas);
          } else if (redatas.code == 500) {
            that.toast(redatas.message)
          }
        }
      },
      fail: err => {
        wx.hideLoading()
        this.toast(err)
      }
    })
  },
  // 修改接口请求返回内容的数据类型，都改为字符串型
  handleResData(str) {
    var _str = str
    for (var i = true; i == true;) {
      var i = /[:][0-9]{18,}[,]?/.test(_str)
      if (i == true) {
        var handlestr = /[:][0-9]{18,}[,]?/.exec(_str)
        var handlestr2 = /[0-9]{18,}/.exec(handlestr[0])
        _str = _str.replace(handlestr[0], ':"' + handlestr2[0] + '",')
      }
    }
    _str = _str.replace(/[,][}]/g, '}')
    return JSON.parse(_str)
  },
  //全局获取图片上传参数
  globalData: {
    url: '',
    token: '',
    system: 0, //0ios1,1安卓
    o_index: '',
    index: '',
    sign_status: 0,
    local_index: false,
    userId: '', // 用户ID
    tabbar_index: 0,
    theme_color:''
  },
  toast: (msg, time) => {
    wx.showToast({
      icon: 'none',
      mask: true,
      title: msg,
      duration: time ? time : 1500
    });
  },
  success: (msg, time) => {
    wx.showToast({
      title: msg,
      icon: 'success',
      duration: time ? time : 2000
    })
  },
  loading: (msg) => {
    wx.showLoading({
      mask: true,
      title: msg ? msg : '加载中..'
    });
  },
  // 设置tab颜色背景
  set_nav: () => {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#ff0000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },
  // 小程序更新检查
  autoUpdate: function () {
    let _this = this
    // 获取小程序更新机制的兼容，由于更新的功能基础库要1.9.90以上版本才支持，所以此处要做低版本的兼容处理
    if (wx.canIUse('getUpdateManager')) {
      // wx.getUpdateManager接口，可以获知是否有新版本的小程序、新版本是否下载好以及应用新版本的能力，会返回一个UpdateManager实例
      const updateManager = wx.getUpdateManager()
      // 检查小程序是否有新版本发布，onCheckForUpdate：当小程序向后台请求完新版本信息，会通知这个版本告知检查结果
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          // 检测到新版本，需要更新，给出提示
          wx.showModal({
            title: '更新提示',
            content: '检测到新版本，是否下载新版本并重启小程序',
            success: function (res) {
              if (res.confirm) {
                // 用户确定更新小程序，小程序下载和更新静默进行
                _this.downLoadAndUpdate(updateManager)
              } else if (res.cancel) {
                // 若用户点击了取消按钮，二次弹窗，强制更新，如果用户选择取消后不需要进行任何操作，则以下内容可忽略
                wx.showModal({
                  title: '提示',
                  content: '本次版本更新涉及到新功能的添加，旧版本将无法正常使用',
                  showCancel: false, // 隐藏取消按钮
                  confirmText: '确认更新', // 只保留更新按钮
                  success: function (res) {
                    if (res.confirm) {
                      // 下载新版本，重启应用
                      _this.downLoadAndUpdate(updateManager)
                    }
                  }
                })
              }
            }
          })
        }
      })
    } else {
      // 在最新版本客户端上体验小程序
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试',
      })
    }
  },
  // 下载小程序最新版本并重启
  downLoadAndUpdate: function (updateManager) {
    wx.showLoading()
    // 静默下载更新小程序新版本，onUpdateReady：当新版本下载完成回调
    updateManager.onUpdateReady(function () {
      wx.hideLoading()
      // applyUpdate：强制当前小程序应用上新版本并重启
      updateManager.applyUpdate()
    })
    // onUpdateFailed：当新版本下载失败回调
    updateManager.onUpdateFailed(function () {
      // 下载新版本失败
      wx.showModal({
        title: '已有新版本',
        content: '新版本已经上线了，请删除当前小程序，重新搜索打开',
      })
    })
  }
});
